using System;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using E4RPManager.DataSets;

namespace E4RPManager.Controls
{
    public partial class PartnersXtraUserControl : XtraUserControl
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.PartnerSaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public PartnersXtraUserControl()
        {
            InitializeComponent();
            gridView.DoubleClick += GridViewDoubleClick;
        }

        #region Private Methods

        private void SetGridDataSource()
        {
            var dataSet = _controller.GetPartners();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Parceiro.TableName;
        }

        private void ShowPartner(long documentId)
        {
            int handle = gridView.FocusedRowHandle;
            var window = new PartnerXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
            if (documentId > 0)
                gridView.FocusedRowHandle = handle;
        }

        #endregion


        public void NewPartner()
        {
            ShowPartner(-1);
        }

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "PartnersXtraUserControl"; }
        }


        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var partner = (ParceiroDataSet.ParceiroRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (partner == null)
                return;
            ShowPartner(partner.Id);
        }
    }
}
